<?php
/**
 * Created by PhpStorm.
 * User: chenyunwen01
 * Date: 2015/3/31
 * Time: 18:46
 */
if (!function_exists('success')) {
    function success($data = false, $message = 'success', $code = 0)
    {
        return response()->json(array(
            'code'    => $code,
            'message' => $message,
            'data'    => $data
        ));
    }
}

if (!function_exists('error')) {
    function error($code = 100, $message = 'failed', $data = false)
    {
        return response()->json(array(
            'code'    => $code,
            'message' => $message,
            'data'    => $data
        ));
    }
}

if (!function_exists('static_path')) {
    /**
     * Generate an asset path for the application.
     *
     * @param  string $path
     * @param  bool $secure
     * @return string
     */
    function static_path($path)
    {
        $dist = '/assets/';
        $path = trim($path, '/');

        return url($dist . $path);
    }
}


/**
 * packRawCriteria
 *
 * @param array $criteria
 * @return multitype:
 */
function packRawCriteria(array $criteria)
{
    $where = '';
    $data = array();
    $optmap = array(
        'gte'  => ' >= ',
        'gt'   => ' > ',
        'lte'  => ' <= ',
        'lt'   => ' < ',
        'ne'   => ' != ',
        'in'   => ' in ( %s ) ',
        'like' => ' like ',
    );

    foreach ((array)$criteria as $row => $value) {

        if ($value === 0) {
            $where [] = $row . ' = ?';
            $data[] = $value;
            continue;
        }

        if ($value != false) {
            if (strstr($row, '__')) {
                list($row, $rule) = explode('__', $row);

                //in 特殊处理
                if (is_array($value) && $row == 'in') {
                    $qstr = '';
                    for ($i = 0; $i < count($value); $i++) {
                        $qstr .= ' ?,';
                    }
                    $qstr = strlen($qstr) > 0 ? substr($qstr, 0, (strlen($qstr) - 1)) : $qstr;

                    $where [] = $row . sprintf($optmap[$rule], $qstr);

                } else if ($row == 'like') {
                    $where [] = $row . $optmap[$rule] . '%?%';
                } else {
                    $where [] = $row . $optmap[$rule] . '?';
                }

            } else {
                $where [] = $row . ' = ?';
            }
            $data[] = $value;
        }
    }

    if (!empty($where)) {
        $where = implode(' and ', $where);
    }

    if (empty($where)) {
        return false;
    }

    return compact('where', 'data');
}

/**
 * packRawCriteria
 *
 * @param array $criteria
 * @return multitype:
 */
function packSqlCriteria(array $criteria)
{
    $where = '';
    $optmap = array(
        'gte'    => ' >= ',
        'gt'     => ' > ',
        'lte'    => ' <= ',
        'lt'     => ' < ',
        'ne'     => ' != ',
        'in'     => ' in ( %s ) ',
        'like'   => ' like ',
        'isnull' => ' = ""',
    );
    foreach ((array)$criteria as $row => $value) {
        if ($value === 0) {
            $where [] = sprintf('%s %s %s', $row, '=', $value);
            continue;
        }

        if ($value !== false) {

            // 转化字符串
            if (is_array($value) && !empty($value)) {
                $value = array_map(function ($a) {
                    return is_numeric($a) ? $a : '"' . $a . '"';
                }, $value);
            }

            // 逻辑判断
            if (strstr($row, '__')) {
                list($row, $rule) = explode('__', $row);

                //in 特殊处理
                if (is_array($value) && !empty($value) && $rule == 'in') {
                    $qstr = implode(',', $value);
                    $where [] = $row . sprintf($optmap[$rule], $qstr);
                } else if ($rule == 'like' && !empty($value)) {
                    $where [] = $row . $optmap[$rule] . '"%' . $value . '%"';
                } else if ($rule == 'isnull') {
                    $where [] = $row . $optmap[$rule];
                } else if (!empty($value)) {
                    $where [] = $row . $optmap[$rule] . $value;
                }
            } else if (!empty($value)) {
                $where [] = $row . ' = ' . $value;
            }
        }
    }

    if (!empty($where)) {
        $where = implode(' and ', $where);
    }

    return $where;
}

function pagecache_start($cachetime = 120, $suffix = '', $dest = '/tmp')
{
    $param = '';
    if (!empty($_GET)) {
        try {
            $param = implode('', array_keys($_GET)) . implode('', array_values($_GET));
        } catch (Exception $e) {
        }
    }
    $cachefile = $dest . '/' . sha1($_SERVER['REQUEST_URI'] . $param) . $suffix;
    ob_start();

    //本地
    if (strpos(gethostname(), 'BF-') !== false) {
        $cachetime = 0;
    }

    if (file_exists($cachefile) && (time() - filemtime($cachefile) < $cachetime)) {
        include($cachefile);
        ob_end_flush();
        exit;
    }
}

function pagecache_end($suffix = '', $dest = '/tmp')
{
    $param = '';
    if (!empty($_GET)) {
        try {
            $param = implode('', array_keys($_GET)) . implode('', array_values($_GET));
        } catch (Exception $e) {
        }
    }

    $lock = fopen($dest . '/' . sha1($_SERVER['REQUEST_URI']) . '.lock', 'w');
    if (flock($lock, LOCK_EX | LOCK_NB)) { // do an exclusive lock
        $cachefile = $dest . '/' . sha1($_SERVER['REQUEST_URI'] . $param) . $suffix;
        $fp = fopen($cachefile, 'w');
        fwrite($fp, ob_get_contents());
        fclose($fp);

        flock($lock, LOCK_UN); // release the lock
        fclose($lock);
    }
    ob_end_flush();
}

function pagecache_clean($uri, $dest = '/tmp')
{
    $cachefile = $dest . '/' . sha1($uri);
    if (file_exists($cachefile)) {
        unlink($cachefile);
    }
}